package com.v.air.app.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.v.air.app.BaseActivity;
import com.v.air.app.R;
import com.v.air.app.adapter.DeviceAdapter;
import com.v.air.app.adapter.StationListAdapter;
import com.v.air.app.bean.DeviceBean;
import com.v.air.app.bean.PM25Bean;
import com.v.air.app.http.HttpMethod;
import com.v.air.app.http.HttpResultInterface;
import com.v.air.app.interfaces.StationClickListener;
import com.v.air.app.tools.PreferencesTool;
import com.v.air.app.tools.StringTool;
import com.v.air.app.tools.StringUtils;
import com.v.air.app.ui.MainActivity.DatePushReceiver;
import com.v.air.app.util.DateTimeTool;
import com.v.air.app.widget.CustomLeftTextView;
import com.v.air.app.widget.CustomRightTextView;
import com.v.air.app.widget.CustomTextView;

public class ViewActivity extends BaseActivity {
	protected Resources res;
	protected ImageButton moreImageView;
	protected TextView cityTextView;
	protected TextView dateTextView;
	protected TextView titleTextView;

	protected ListView listView;
	protected StationListAdapter adapter;
	protected ListView tlistView;
	protected DeviceAdapter deviceAdapter;
	protected List<DeviceBean> deviceList;
	protected List<PM25Bean> dataList = new ArrayList<PM25Bean>();
	// 室外PM
	protected CustomLeftTextView pmAirTextView;
	protected TextView pmAirNameTextView;
	protected TextView pmAirstateTextView;

	protected TextView pmAirStationTextView;
	// 室内PM
	protected CustomRightTextView pmHomeTextView;
	protected TextView pmHomeNameTextView;
	protected TextView pmHomestateTextView;
	// 温度
	protected CustomTextView customTextView1;
	protected TextView text1_state;
	// 湿度
	protected CustomTextView customTextView2;
	protected TextView text2_state;
	// ppm
	protected CustomTextView customTextView3;
	protected TextView text3_state;
	// TPOC
	protected CustomTextView customTextView4;
	protected TextView text4_state;

	protected DatePushReceiver datePushReceiver;
	protected long exitTime;
	protected Timer timer;
	// API 更新间隔
	protected String api_name = "";
	protected int api_num = 0;
	protected int device_num = 0;
	// API分页
	protected int pager = 1;
	protected int pagerSize = 6;
	private int lastPosition = -1;

	protected B3UARTConnector B3Uart_thread = null;

	@Override
	public int bindLayout() {
		return R.layout.main;
	}

	@Override
	public void initView(View view) {
		initHead(view);
		res = this.getResources();
		deviceList = DeviceBean.deviceList();
		initTopView(view);
		initButtomView(view);
	}

	public void initButtomView(View view) {
		pmHomeTextView = (CustomRightTextView) view.findViewById(R.id.pm_home);
		pmHomeTextView.setColor(res.getColor(R.color.pm_color_optimal));
		pmHomeTextView.setTextColor(res.getColor(R.color.pm_color_optimal));
		pmHomeNameTextView = (TextView) view.findViewById(R.id.pm_home_name);
		pmHomestateTextView = (TextView) view.findViewById(R.id.pm_home_state);
		pmHomeNameTextView.setTextColor(res.getColor(R.color.pm_color_optimal));
		pmHomestateTextView
				.setTextColor(res.getColor(R.color.pm_color_optimal));

		pmAirTextView = (CustomLeftTextView) view.findViewById(R.id.pm_air);
		pmAirTextView.setColor(res.getColor(R.color.pm_color_optimal));
		pmAirTextView.setTextColor(res.getColor(R.color.pm_color_optimal));
		pmAirNameTextView = (TextView) view.findViewById(R.id.pm_air_name);
		pmAirStationTextView = (TextView) view
				.findViewById(R.id.pm_air_name_station);
		pmAirstateTextView = (TextView) view.findViewById(R.id.pm_air_state);
		pmAirNameTextView.setTextColor(res.getColor(R.color.pm_color_optimal));
		pmAirstateTextView.setTextColor(res.getColor(R.color.pm_color_optimal));
		pmAirStationTextView.setTextColor(res
				.getColor(R.color.pm_color_optimal));

		customTextView1 = (CustomTextView) view.findViewById(R.id.text1);
		text1_state = (TextView) view.findViewById(R.id.text1_state);
		customTextView1.setColor(res.getColor(R.color.city_color_1));
		customTextView1.setTextColor(res.getColor(R.color.city_color_1));
		customTextView2 = (CustomTextView) view.findViewById(R.id.text2);
		text2_state = (TextView) view.findViewById(R.id.text2_state);
		customTextView2.setColor(res.getColor(R.color.city_color_2));
		customTextView2.setTextColor(res.getColor(R.color.city_color_2));
		customTextView3 = (CustomTextView) view.findViewById(R.id.text3);
		text3_state = (TextView) view.findViewById(R.id.text3_state);
		customTextView3.setColor(res.getColor(R.color.city_color_3));
		customTextView3.setTextColor(res.getColor(R.color.city_color_3));
		customTextView4 = (CustomTextView) view.findViewById(R.id.text4);
		text4_state = (TextView) view.findViewById(R.id.text4_state);
		customTextView4.setColor(res.getColor(R.color.city_color_4));
		customTextView4.setTextColor(res.getColor(R.color.city_color_4));

		tlistView = (ListView) view.findViewById(R.id.list);
		tlistView.setFocusable(false);
		deviceAdapter = new DeviceAdapter(this);
		tlistView.setAdapter(deviceAdapter);
		refreshDevice();
	}

	public void initTopView(View view) {
		moreImageView = (ImageButton) view.findViewById(R.id.more);
		cityTextView = (TextView) view.findViewById(R.id.city_name);
		dateTextView = (TextView) view.findViewById(R.id.date);
		titleTextView = (TextView) view.findViewById(R.id.app_title);
		listView = (ListView) view.findViewById(R.id.listview);
		listView.setFocusable(true);
		adapter = new StationListAdapter(this, new StationClickListener() {
			@Override
			public void onClick(PM25Bean bean, int pose) {
				if (bean != null) {
					lastPosition = bean.getPosition();
					setLeftRightText(bean.getPm2_5(), true,
							bean.getPosition_name());
				} else {
					setLeftRightText(0, true, "");
				}
			}
		});
		listView.setAdapter(adapter);
		listView.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View view,
					int arg2, long arg3) {
				TextView nameTextView = (TextView) view.findViewById(R.id.name);
				PM25Bean bean = (PM25Bean) nameTextView.getTag();
				if (bean != null) {
					lastPosition = bean.getPosition();
					setLeftRightText(bean.getPm2_5(), true,
							bean.getPosition_name());
				} else {
					setLeftRightText(0, true, "");
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		cityTextView.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean flag) {
				if (flag) {
					cityTextView.setTextColor(res.getColor(R.color.green));
				} else {
					cityTextView.setTextColor(res.getColor(R.color.white));
				}
			}
		});
		titleTextView.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean flag) {
				if (flag) {
					titleTextView.setTextColor(res.getColor(R.color.green));
				} else {
					titleTextView.setTextColor(res.getColor(R.color.white));
				}
			}
		});
	}

	/**
	 * 室内室外数据
	 * 
	 * @param pm
	 * @param flag
	 */
	protected void setLeftRightText(float pm, boolean flag, String station) {
		int color = DeviceBean.getPMstateColor(pm, res);
		if (flag) {
			if (pm == 0) {
				pmAirTextView.setText("");
				pmAirstateTextView.setText("");
				pmAirStationTextView.setText("");
			} else {
				pmAirTextView.setText(pm + "");
				pmAirstateTextView.setText(DeviceBean.getPMstate(pm, res));
				pmAirStationTextView.setText(station);
			}
			pmAirTextView.setTextColor(color);
			pmAirTextView.setColor(color);
			pmAirstateTextView.setTextColor(color);
			pmAirNameTextView.setTextColor(color);
			pmAirStationTextView.setTextColor(color);
		} else {
			if (pm == 0) {
				pmHomeTextView.setText("");
				pmHomestateTextView.setText("");
			} else {
				pmHomeTextView.setText(pm + "");
				pmHomestateTextView.setText(DeviceBean.getPMstate(pm, res));
			}
			pmHomeTextView.setTextColor(color);
			pmHomeTextView.setColor(color);
			pmHomestateTextView.setTextColor(color);
			pmHomeNameTextView.setTextColor(color);
		}
	}

	/**
	 * app每分钟刷新
	 */
	protected void resetView_Minute() {
		api_num += 1;
		if (myApplication.getCityBean() != null) {
			if (dataList == null
					|| dataList.size() == 0
					|| StringUtils.isEmpty(api_name)
					|| (!api_name.equals(myApplication.getCityBean()
							.getNumber()))) {
				getFromNet(myApplication.getCityBean().getNumber());
			} else {
				if (api_num == 5) {
					getFromNet(myApplication.getCityBean().getNumber());
				}
			}
		}
		// 刷新pm2.5 API 列表
		setPm2_5APIData();
		// 1分钟 刷新 室外数据
		setPmAirData();
	}

	/**
	 * app每秒刷新
	 */
	protected void resetView_second() {
		if (myApplication.getCityBean() != null) {
			cityTextView.setText(myApplication.getCityBean().getName());
		}
		dateTextView.setText(DateTimeTool.getDateTime());
		refreshDataFromDevice();
		device_num += 1;
		if (device_num == 10) {
			// 刷新设备列表
			refreshDevice();
			device_num = 0;
		}
	}

	/**
	 * 更新设备数据
	 */
	protected void refreshDataFromDevice() {
		// 室内PM2.5
		float pm = PreferencesTool.getFloat(getContext(), "pm", 0);
		setLeftRightText((int) pm, false, "");
		float temperature = PreferencesTool.getFloat(getContext(),
				"temperature", 0);
		if (temperature == 0) {
			customTextView1.setText("");
			text1_state.setText("");
		} else {
			customTextView1.setText(String.valueOf(temperature));
			text1_state.setText(DeviceBean
					.getTemperatureState(temperature, res));
			if (temperature >= 1000) {
				customTextView1.setTextSize(46);
			} else {
				customTextView1.setTextSize(56);
			}
		}
		float humidity = PreferencesTool.getFloat(getContext(), "humidity", 0);
		if (humidity == 0) {
			customTextView2.setText("");
			text2_state.setText("");
		} else {
			customTextView2.setText(String.valueOf(humidity));
			text2_state.setText(DeviceBean.getHumidityState(humidity, res));
			if (humidity >= 1000) {
				customTextView2.setTextSize(46);
			} else {
				customTextView2.setTextSize(56);
			}
		}
		float co2 = PreferencesTool.getFloat(getContext(), "co2", 0);
		if (co2 == 0) {
			customTextView3.setText("");
			text3_state.setText("");
		} else {
			customTextView3.setText(String.valueOf(co2));
			text3_state.setText(DeviceBean.getPpmState(co2, res));
			if (co2 >= 1000) {
				customTextView3.setTextSize(46);
			} else {
				customTextView3.setTextSize(56);
			}
		}
		float tvoc = PreferencesTool.getFloat(getContext(), "tvoc", 0);
		if (tvoc == 0) {
			customTextView4.setText("");
			text4_state.setText("");
		} else {
			customTextView4.setText(String.valueOf(tvoc));
			text4_state.setText(DeviceBean.getTvocState(tvoc, res));
			if (tvoc >= 1000) {
				customTextView4.setTextSize(46);
			} else {
				customTextView4.setTextSize(56);
			}
		}

		DeviceBean deviceBean = new DeviceBean(3, "大厅", pm, temperature,
				humidity, co2, tvoc);
		for (int i = 0, len = deviceList.size(); i < len; i++) {
			if (deviceList.get(i).getId() == 3) {
				deviceList.set(i, deviceBean);
			}
		}
	}

	/**
	 * API 数据
	 */
	private void setPm2_5APIData() {
		if (dataList != null && dataList.size() > 0) {
			int len = dataList.size();
			if (len > pagerSize) {
				int start = (pager - 1) * pagerSize;
				int end = pager * pagerSize;
				if (len < start) {
					pager -= 1;
					if (pager <= 0) {
						pager = 1;
					}
					setPm2_5APIData();
				} else if (start < len && len < end) {
					adapter.setData(dataList.subList(start, len));
					pager = 1;
				} else if (start < len && len > end) {
					adapter.setData(dataList.subList(start, end));
					pager += 1;
				}
			} else {
				adapter.setData(dataList);
			}
			adapter.notifyDataSetChanged();
		}
		// else {
		// getFromNet(myApplication.getCityBean().getNumber());
		// }
	}

	/**
	 * 1分钟 刷新 室外数据
	 */
	private void setPmAirData() {
		lastPosition += 1;
		if (dataList != null && dataList.size() > 0) {
			PM25Bean bean = null;
			if (dataList.size() <= lastPosition) {
				lastPosition = 0;
			}
			bean = dataList.get(lastPosition);
			if (bean != null) {
				setLeftRightText(bean.getPm2_5(), true, bean.getPosition_name());
			} else {
				setLeftRightText(0, true, "");
			}
		} else {
			setLeftRightText(0, true, "");
		}

	}

	/**
	 * 虚拟设备数据
	 * 
	 * @return
	 */
	private void refreshDevice() {
		if (api_num == 0) {
			Collections.sort(deviceList, new Comparator<DeviceBean>() {
				@Override
				public int compare(DeviceBean lhs, DeviceBean rhs) {
					return (int) (lhs.getPm() - rhs.getPm());
				}
			});
		} else if (api_num == 1) {
			Collections.sort(deviceList, new Comparator<DeviceBean>() {
				@Override
				public int compare(DeviceBean lhs, DeviceBean rhs) {
					return (int) (lhs.getPpm() - rhs.getPpm());
				}
			});
		} else if (api_num == 2) {
			Collections.sort(deviceList, new Comparator<DeviceBean>() {
				@Override
				public int compare(DeviceBean lhs, DeviceBean rhs) {
					return (int) (lhs.getTemperature() - rhs.getTemperature());
				}
			});
		} else if (api_num == 3) {
			Collections.sort(deviceList, new Comparator<DeviceBean>() {
				@Override
				public int compare(DeviceBean lhs, DeviceBean rhs) {
					return (int) (lhs.getHumidity() - rhs.getHumidity());
				}
			});
		} else if (api_num == 4) {
			Collections.sort(deviceList, new Comparator<DeviceBean>() {
				@Override
				public int compare(DeviceBean lhs, DeviceBean rhs) {
					return (int) (lhs.getTvoc() - rhs.getTvoc());
				}
			});
		} else {
			Collections.sort(deviceList, new Comparator<DeviceBean>() {
				@Override
				public int compare(DeviceBean rhs, DeviceBean lhs) {
					return (int) (lhs.getPm() - rhs.getPm());
				}
			});
		}
		deviceAdapter.setData(deviceList);
		deviceAdapter.notifyDataSetChanged();
	}

	/**
	 * API接口
	 * 
	 * @param id
	 */
	public void getFromNet(String id) {
		if (myApplication.getCityBean() != null) {
			api_name = myApplication.getCityBean().getNumber();
			HttpMethod.getInstance().getData(this, HttpMethod.PM_2_5_URL,
					api_name, new HttpResultInterface() {

						@Override
						public void onHttpSuccess(String result) {
							if (StringTool.isVasib(result)) {
								Log.e("onHttpSuccess", result);
								if (result.startsWith("[")) {
									List<PM25Bean> list = new Gson().fromJson(
											result,
											new TypeToken<List<PM25Bean>>() {
											}.getType());
									if (list != null && list.size() > 0) {
										list.remove(list.size() - 1);
										// 过滤数据0
										dataList = filterData(list);
										pager = 1;
										setPm2_5APIData();
										setPmAirData();
									} else {
										adapterClear(api_name);
									}
								} else {
									adapterClear(api_name);
								}
							} else {
								adapterClear(api_name);
							}
							api_num = 0;
						}

						private List<PM25Bean> filterData(List<PM25Bean> list) {
							List<PM25Bean> setList = new ArrayList<PM25Bean>();
							if (list != null && list.size() > 0) {
								for (PM25Bean bean : list) {
									if (bean.getPm2_5() > 0) {
										setList.add(bean);
									}
								}
							}
							Collections.sort(setList,
									new Comparator<PM25Bean>() {
										@Override
										public int compare(PM25Bean lhs,
												PM25Bean rhs) {
											return lhs.getPm2_5()
													- rhs.getPm2_5();
										}
									});

							for (int i = 0, len = setList.size(); i < len; i++) {
								setList.get(i).setPosition(i);
							}
							return setList;
						}

						@Override
						public void onHttpError(int statusCode,
								String responseBody, Throwable e) {
							adapterClear(api_name);
						}

					});
		}
	}

	private void adapterClear(String api_number) {
		setLeftRightText(0, true, "");
		if (dataList != null) {
			dataList.clear();
			adapter.setData(dataList);
		}
		adapter.notifyDataSetChanged();
		if (myApplication.getCityBean() != null) {
			getFromNet(myApplication.getCityBean().getNumber());
		}
	}

	@Override
	public void resume() {

	}

	@Override
	public void destroy() {

	}

	@Override
	public void initData(Context mContext) {
	}

	@Override
	public void initListener() {
	}
}
